package jwt.lab02;

import javax.mail.*;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class SaveAttachments {
	private static String DIR;

	public static void main(String[] args) throws MessagingException, IOException {
		Properties props = Utils.loadProperties(Utils.PROPERTIES_FILE);
		DIR = props.getProperty("attachment.save.dir");

		Session session = Session.getDefaultInstance(props, null);

		Store store = session.getStore(props.getProperty("mail.store.protocol"));
		store.connect(props.getProperty("mail.pop3.host"), props.getProperty("mail.pop3.user"), props.getProperty("mail.pop3.password"));

		Folder folder = store.getFolder("INBOX");
		folder.open(Folder.READ_ONLY);

		Message[] message = folder.getMessages();

		for (int i = 0; i < message.length; i++) {
			System.out.println("Checking mail: " + Utils.normalizeString(message[i].getSubject()));

			if (!(message[i].getContent() instanceof Multipart))
				continue;
			
			Multipart multipart = (Multipart) message[i].getContent();

			for (int j = 0; j < multipart.getCount(); j++) {
				Part part = multipart.getBodyPart(j);

				String disposition = part.getDisposition();

				if ((disposition != null) &&
						((disposition.equals(Part.ATTACHMENT) ||
								(disposition.equals(Part.INLINE))))) {
					saveFile(Utils.normalizeString(part.getFileName()), part.getInputStream());
				}
			}

		}

		folder.close(false);
		store.close();
	}

	private static void saveFile(String fileName, InputStream inputStream) throws IOException {
		File file = new File(DIR + fileName);
		for (int i = 0; file.exists(); i++)
			file = new File(DIR + fileName + i);
		copyStream(inputStream, new FileOutputStream(file));
		System.out.println("Saved file " + fileName + " into " + DIR);
	}

	private static void copyStream(InputStream is, FileOutputStream fos) throws IOException {
		byte[] buffer = new byte[4096];
		int bytes;		
		while (true) {
			bytes = is.read(buffer);
			if (bytes <= 0) break;
			fos.write(buffer, 0, bytes);
		}
		fos.close();
	}

}
